from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 数据库连接配置
DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "mysql+mysqlconnector://root:111111@127.0.0.1/qnn"
    # "mysql+mysqlconnector://root:123456@127.0.0.1/qnn"
)

# 创建数据库引擎（默认不立即连接）
engine = None
SessionLocal = None
Base = declarative_base()

try:
    # 创建数据库引擎
    engine = create_engine(DATABASE_URL, pool_pre_ping=True)
    # 测试连接
    with engine.connect() as conn:
        pass
    # 创建会话本地类
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
except Exception as e:
    print(f"数据库连接失败: {e}")
    engine = None
    SessionLocal = None

# 获取数据库会话的依赖项
def get_db():
    if SessionLocal is None:
        raise Exception("数据库连接未建立")
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()